package com.cn.fw4j.mvc.page.impl;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.fw4j.mvc.page.inter.IPageTemplate;
import com.cn.fw4j.util.request.parameter.OutParam;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FtlTemplate implements IPageTemplate {
	private static Configuration cfg = null; 
	
	@SuppressWarnings("deprecation")
	private void init(HttpServletRequest request){
		if(cfg == null){
			cfg = new Configuration();
			cfg.setServletContextForTemplateLoading(request.getServletContext(), "WEB-INF/ftl");
		}
	}
	
	@Override
	public void Template(String path, OutParam outparam,
			HttpServletRequest request, HttpServletResponse response) {
			init(request);
		if(outparam != null && outparam.size()>0){
			Set<Object> keys = outparam.keySet();
			for(Object key : keys){
				Object value = outparam.get(key);
				if(value instanceof Cookie){
					response.addCookie((Cookie)value);
				}else{
					request.setAttribute(key.toString(), outparam.get(key));
				}
			}
		}
		
		if(path.startsWith("redirect:")){
			path = path.replace("redirect:","");
			try {
				response.sendRedirect(path);
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}else{
			path = path.replace("request:","");
			try {
				Template t = cfg.getTemplate(path.toString()+".ftl");
				response.setContentType("text/html;charset=" + t.getEncoding());
				Map<Object,Object> data = outparam;
				t.process(data, response.getWriter());
			} catch (TemplateException | IOException e) {
				e.printStackTrace();
			}
		}
	}
}
